#include "record_search_impl.h"
#include <fstream>
#include <sstream>
#include <chrono>
#include <iomanip>
#include "base_log.h"
#include "base_utils.h"
#include "common_config_manager.h"
#include "nlohmann/json.hpp"
#include "record_search_cache.h"
namespace El {
namespace Record {

RecordSearchPtr IRecordSearch::create()
{
    return std::make_shared<CRecordSearch>();
}

CRecordSearch::CRecordSearch()
{
    // 从配置中获取存储路径
    auto config = Common::ConfigManager::GetInstance().GetConfig("storage");
    if (!config.empty() && config.contains("mountPath")) {
        storePath_ = config["mountPath"].get<std::string>();
    } else {
        storePath_ = "/mnt/udisk";
        LOG_ERROR("storage config is empty");
    }
}

bool CRecordSearch::searchVideo(int32_t ch, TimePoint start, TimePoint end)
{
    if (ch < 0 || start >= end) {
        LOG_ERROR("Invalid search parameters: ch={}, start={}, end={}", ch, Base::utcToString(start).c_str(),
                  Base::utcToString(end).c_str());
        return false;
    }

    searchResults_ = RecordSearchCache::GetInstance().SearchVideo(ch, start, end);
    currentIndex_ = 0;
    return true;
}

bool CRecordSearch::findNextVideo(int32_t count, int32_t &found, std::vector<VideoFileInfo> &fileList)
{
    if (count <= 0) {
        LOG_ERROR("Invalid count parameter: {}", count);
        return false;
    }

    fileList.clear();
    found = 0;

    // 返回指定数量的搜索结果
    while (currentIndex_ < searchResults_.size() && found < count) {
        fileList.push_back(searchResults_[currentIndex_]);
        currentIndex_++;
        found++;
    }

    return true;
}

bool CRecordSearch::closeVideo()
{
    searchResults_.clear();
    currentIndex_ = 0;
    return true;
}

bool CRecordSearch::searchImage(int32_t ch, TimePoint start, TimePoint end)
{
    if (ch < 0 || start >= end) {
        LOG_ERROR("Invalid search parameters: ch={}, start={}, end={}", ch, Base::utcToString(start).c_str(),
                  Base::utcToString(end).c_str());
        return false;
    }

    // 清空之前的搜索结果并使用 RecordSearchCache 搜索
    imageResults_ = RecordSearchCache::GetInstance().SearchImage(ch, start, end);
    imageIndex_ = 0;
    return true;
}

bool CRecordSearch::findNextImage(int32_t count, int32_t &found, std::vector<ImageFileInfo> &fileList)
{
    if (count <= 0) {
        LOG_ERROR("Invalid count parameter: {}", count);
        return false;
    }

    fileList.clear();
    found = 0;

    while (imageIndex_ < imageResults_.size() && found < count) {
        fileList.push_back(imageResults_[imageIndex_]);
        imageIndex_++;
        found++;
    }

    return true;
}

bool CRecordSearch::closeImage()
{
    imageResults_.clear();
    imageIndex_ = 0;
    return true;
}

} // namespace Record
} // namespace El
